/**
 * 微信登录授权反复弹窗到你允许为止控制器
 * 使用方法: 在每个(作为入口的)pages里面的js引用,并运行login方法即可
 * 不推荐在app.js上使用.有可能会导致重复登录
 * */

// promise ajax 封装
import $services from '../services/index.js'

// 登录授权(反复弹到你授权为止)
function auth(callBack) {
  var _callBack = callBack
  var _code = null

  wx.login({
    success(res) {
      _code = res.code  //存起code
      wx.getUserInfo({
        complete(userComp) {
          if (userComp.signature && userComp.errMsg.indexOf('ok') > -1) { //授权成功
            userComp.code = _code
            _callBack(userComp)
          } else {  //失败
            wx.showModal({
              content: '为了保证您能正常使用本小程序,请允许获取您的公开信息(头像,昵称)',
              success(confirmRes) {
                if (confirmRes.cancel) {  //取消则继续让他选
                  auth(_callBack)
                } else { //成功就弹setting
                  wx.openSetting({
                    complete(openSetRes) {
                      auth(_callBack) //不允许就继续弹
                    }
                  })
                }
              }
            })
          }
        }
      })
    },
    fail(err) {
      wx.showModal({
        content: '微信登录失败,请检查您的网络是否正常',
        showCancel: false
      })
    }
  })
}

//得到code和userInfo后ajax请求与注册
function login(app) {
  return new Promise((reslove) => {
    auth(function (userInfoAndCode) {
      var loginData = {
        code: userInfoAndCode.code,
        rawData: userInfoAndCode.rawData,
        signature: userInfoAndCode.signature,
        encryptedData: userInfoAndCode.encryptedData,
        iv: userInfoAndCode.iv
      }

      wx.setStorageSync('loginData', loginData)

      //已经受过权直接返回,否则调用login后返回
      if(app.globalData.userInfo) {
        wx.setStorage({
          key: 'userInfo',
          data: app.globalData.userInfo,
        })
        reslove(userInfoAndCode)
      } else {
        $services.login.login(loginData).then(result => {
          result.data.user.userId = result.data.user.uid  //userId是没有用的,用uid代替
          app.globalData.userInfo = result.data.user
          wx.setStorageSync('userInfo', result.data.user)
          reslove(userInfoAndCode)
        }, error => {
          wx.showModal({
            content: '服务端正忙,请稍后重试',
            showCancel: false
          })
        }).catch(err => {
          wx.showModal({
            content: '服务端正忙,请稍后重试',
            showCancel: false
          })
        })
      }


    })
  })
}

module.exports = {
  auth,
  login
}